<template>
  <div class="product-main">
    <el-collapse style="text-indent: 1em; padding-bottom: 10px; border-bottom: 1px solid #fff; background-color: #fff;">
      <el-collapse-item title="商品管理介绍">
        <div>商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情</div>
      </el-collapse-item>
    </el-collapse>

    <!-- 条件查询 -->
    <el-collapse class="margin-30">
      <el-collapse-item title="条件查询">
        <el-form ref="productListForm" :model="searchProductForm" label-width="100px" size="mini">
          <el-row :gutter="20">
            <el-col :span="6" :offset="0">
              <el-form-item label="商品名称">
                <el-input v-model="searchProductForm.name" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="商品货号">
                <el-input v-model="searchProductForm.productSn" />
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="品牌">
                <el-select v-model="searchProductForm.brandId" clearable placeholder="请选择">
                  <el-option v-for="item in BrandList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="0">
              <el-form-item label="上架状态">
                <el-select v-model="searchProductForm.publishStatus" clearable placeholder="请选择">
                  <el-option label="上架" :value="1" />
                  <el-option label="下架" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6" :offset="0">
              <el-form-item label="审核状态">
                <el-select v-model="searchProductForm.verifyStatus" clearable placeholder="请选择">
                  <el-option label="审核通过" :value="1" />
                  <el-option label="未审核" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 按钮 -->
          <el-form-item>
            <el-button @click="getResetProductList">重置</el-button>
            <el-button type="primary" @click="getSerchProduct">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <!-- 商品列表 -->
    <el-card shadow="never" class="margin-30" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-button type="primary" size="mini" @click="goGoods()">新增</el-button>
        <el-button style="margin-left: 13px;" type="primary" size="mini">导出商品列表excel文件</el-button>
      </div>
      <!-- card body -->
      <el-table :data="productList" border stripe>
        <el-table-column prop="col.id" label="#" type="index" width="50" align="center" />
        <el-table-column label="商品图片" width="150" align="center">
          <template slot-scope="scope">
            <el-image style="height: 100px;" :src="scope.row.pic" fit="fill" :lazy="true" />
          </template>
        </el-table-column>
        <el-table-column prop="keywords" label="商品名称" align="center" />
        <el-table-column label="商品价格" width="150" align="center">
          <template slot-scope="scope">
            <div>原价: &nbsp;{{ scope.row.originalPrice }}</div>
            <div>现价: &nbsp;{{ scope.row.price }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="商品类别" width="150" align="center" />
        <el-table-column prop="keywords" label="标签" width="150" align="center">
          <!-- 新品状态:0->不是新品；1->新品 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.newStatus"
              inactive-text="最新"
              :active-value="1"
              :inactive-value="0"
              @change="getNewStatus(scope.row.newStatus, scope.row.id, 1)"
            />
            <el-switch
              v-model="scope.row.recommendStatus"
              inactive-text="推荐"
              :active-value="1"
              :inactive-value="0"
              @change="getNewStatus(scope.row.newStatus, scope.row.id, 2)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="keywords" label="标签2" width="150" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.publishStatus"
              :active-value="1"
              :inactive-value="0"
              inactive-text="发布"
              @change="getNewStatus(scope.row.newStatus, scope.row.id, 3)"
            />
            <el-switch
              v-model="scope.row.verifyStatus"
              inactive-text="审核"
              :active-value="1"
              :inactive-value="0"
              @change="getNewStatus(scope.row.newStatus, scope.row.id, 4)"
            />
          </template>
        </el-table-column>
        <el-table-column label="sku" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="getEditSkuList(scope.row.id)">编辑sku</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量(默认:KG)" width="150" align="center" />
        <el-table-column prop="sort" label="排序" width="150" align="center" />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="goEditIdPage(scope.row.id)">编辑</el-button>
            <el-button style="color: #f00;" type="text" size="mini" @click="getProductDel(scope.row.id)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          style="margin-top: 10px; text-align: center;"
          :current-page="start"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="limit"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- sku -->
    <el-dialog title="sku列表" :visible.sync="dialogVisible" width="70%">
      <el-row :gutter="20">
        <el-col :span="1" :offset="22">
          <el-button type="primary" size="mini" @click="addSkuList">新增</el-button>

        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col v-if="pmsSkuStockList.length" :span="24" :offset="0">
          <el-table style="margin-top: 30px;" :data="pmsSkuStockList" border stripe>
            <el-table-column fixed="left" label="#" type="index" align="center" width="50" />
            <el-table-column label="图片" align="center" width="100">
              <template slot-scope="scope">
                <el-upload
                  :action="uploadFileOss"
                  :headers="token"
                  :show-file-list="false"
                  :on-success="handleSkuPic"
                  :before-upload="beforeAvatarUpload"
                  style="width: 80px; height: 80px;"
                  @click.native="handlPicUpload(scope.row.tempId,scope.row)"
                >
                  <el-image v-if="scope.row.pic" style="width: 70px; height: 70px;" :src="scope.row.pic" />
                  <i
                    v-else
                    style="width: 80px; height: 80px; line-height: 80px;"
                    class="el-icon-plus avatar-uploader-icon"
                  />
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="颜色" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.color" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="大小" align="center" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.size" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="库存" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="预警库存" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lowStock" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="锁定库存" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.lockStock" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="sku编码" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCode" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="价格" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="销量" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sale" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="150">
              <template slot-scope="scope">
                <el-button type="text" size="mini" style="color:#f00" @click="removeSkuList(scope.row.id)">删除</el-button>
                <el-button type="text" size="mini" @click="getupdateProductAndSkus">修改编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mix from '@/mixins'
import { productsByPage, switchNewStatus, switchRecommandStatus, switchPublishStatus, switchVerifyStatus, productDel, productSkusDetail, updateProductAndSkus } from '@/api/product'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'ProductList',
  mixins: [mix],
  data() {
    return {
      searchProductForm: {},
      BrandList: [],
      productList: [],
      pmsSkuStockList: [], // sku列表
      product: {},
      dialogVisible: false,
      del: true
    }
  },
  created() {
    this.getProductList()
  },
  mounted() {
    this.getBrandList()
  },
  methods: {
    // 单独编辑sku
    async getEditSkuList(id) {
      this.dialogVisible = true
      // 获取被编辑的商品信息
      const res = await productSkusDetail(id)
      console.log(res)
      const { data: { skus, product }, success } = res
      if (success) {
        this.product = product
        this.pmsSkuStockList = skus
        const jsonArr2 = []
        skus.forEach(item => {
          jsonArr2.push(JSON.parse(item.spData))
        })
        jsonArr2.forEach((item1, idx) => {
          item1.forEach(item2 => {
            if (item2.key === '颜色') {
              this.$set(this.pmsSkuStockList[idx], 'color', item2.value)
            } else {
              this.$set(this.pmsSkuStockList[idx], 'size', item2.value)
            }
          })
        })
      }
    },
    // 新增sku
    addSkuList() {
      this.pmsSkuStockList.push({
        tempId: uuidv4(),
        'lockStock': '', // 锁定库存
        'lowStock': '', // 库存警戒线
        'pic': '', // 图片
        'price': '', // 当前价格
        'promotionPrice': '', // 单品促销价格
        'sale': '', // 销量
        'skuCode': '', // sku的编码,手动填写
        // spData:  [{"key":"颜色","value":"蓝色"},{"key":"容量","value":"32G"}]
        // 'spData': 'string', // sku属性，json格式String类型 ,
        'stock': '', // 库存
        color: '',
        size: ''
      })
    },
    // 删除对应sku
    removeSkuList(id) {
      this.$confirm('是否删除sku, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idx = this.pmsSkuStockList.findIndex(item => item.id === id)
        this.pmsSkuStockList.splice(idx, 1)
        this.del = false
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getupdateProductAndSkus()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 更新商品
    async getupdateProductAndSkus() {
      this.doAddProduct()
      const res = await updateProductAndSkus({
        pmsSkuStockList: this.pmsSkuStockList,
        product: this.product
      })
      const { message, success } = res
      if (success) {
        if (this.del) {
          this.$message.success('更新成功')
        }
      } else {
        this.$message.warning(message)
      }
    },

    // 规整数据
    doAddProduct() {
      // 添加sku列表
      const tempSkuList = []
      this.pmsSkuStockList.forEach(item => {
        tempSkuList.push({
          ...item,
          spData: JSON.stringify([
            {
              key: '颜色',
              value: item.color
            },
            {
              key: '大小',
              value: item.size
            }
          ])
        })
      })
      this.pmsSkuStockList = tempSkuList
    },
    // 编辑商品
    goEditIdPage(productId) {
      this.$router.push({ name: 'addProductDetail', params: { productId }})
    },
    // 删除商品
    getProductDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await productDel(id)
        const { success } = res
        if (success) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getProductList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 前往新增页
    goGoods() {
      this.$router.push({ name: 'addProductDetail' })
    },

    // 标签 状态改变
    async getNewStatus(status, productId, isWho) {
      let api
      if (isWho === 1) {
        api = switchNewStatus
      } else if (isWho === 2) {
        api = switchRecommandStatus
      } else if (isWho === 3) {
        api = switchPublishStatus
      } else if (isWho === 4) {
        api = switchVerifyStatus
      }
      const res = await api({ productId, status })
      const { success, message } = res
      if (success) {
        this.$message.success('修改成功')
      } else {
        this.$message.error(message)
      }
    },

    // 重置
    getResetProductList() {
      this.searchProductForm = {}
      this.getProductList()
    },

    // 搜索
    getSerchProduct() {
      this.getProductList()
    },

    // 获取商品列表
    async getProductList() {
      const res = await productsByPage(this.start, this.limit, this.searchProductForm)
      console.log(res)
      const { success, message, data: { rows, total }} = res
      if (success) {
        this.productList = rows
        this.total = total
      } else {
        this.$message.error(message)
      }
    },
    // 分页
    handleSizeChange(val) {
      this.limit = val
      this.start = 1
      this.getProductList()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.start = val
      this.getProductList()
      // console.log(`当前页: ${val}`);
    }
  }
}
</script>

<style lang="scss" scoped>
.product-main {

  ::v-deep .el-form-item__label {
    font-size: 14px;
    font-weight: 500;
  }

  ::v-deep .el-collapse-item__header {
    text-indent: 1em;
  }
}
</style>
